<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>嵌套表格2</title>
    <style>
        #cwsNestTable {
            font-size: 9pt;
            word-break: break-all;
            cursor: default;
            BORDER: 1px solid #cccccc;
            border-collapse: collapse;
            border-Color: #cccccc;
            align: center;
        }

        .cwsThead {
            /*background-color:#eeeeee;*/
            height: 20px;
        }

        #cwsNestTable td {
            border: 1px solid #cccccc;
            height: 20px;
        }

        .imgBtn {
            width: 22px;
            height: 22px;
            filter: alpha(opacity=50);
            -moz-opacity: 0.5;
            -khtml-opacity: 0.5;
            opacity: 0.5;
            cursor: pointer;
        }

        .imgBtnHover {
            -moz-opacity: 1;
            -khtml-opacity: 1;
            opacity: 1;
        }

        .paginator {
            margin: 5px 0;
        }

        .search-box input,select {
            vertical-align:middle;
        }
        .search-box input:not([type="radio"]):not([type="button"]):not([type="checkbox"]):not([type="submit"]) {
            width: 80px;
            line-height: 20px; /*否则输入框的文字会偏下*/
        }
        .search-box {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
        }
        .cond-span {
            display: flex;
            float: left;
            align-items: center;
            text-align: left;
            width: 25%;
            height: 32px;
            margin: 3px 0;
        }
        .cond-title {
            margin: 0;
            padding-right: 3px;
            width: 35%;
            text-align: right;
        }

        .tSearch {
            background: url('public/resource/images/search.png') no-repeat left;
            border: 0;
            padding-left:12px;
            vertical-align: middle;
            cursor:pointer;
            height:21px;
            width:21px;
        }

        .row-add {
            background-color: #FAF0E6;
        }
        .row-pull {

        }
    </style>
    <script th:inline="javascript">
        // 删除后重新排序
        function refreshSerialNo(nestFieldName) {
            var trList = $("#cwsNestTable_" + nestFieldName).find("tr");
            for (var i=1;i<trList.length;i++) {
                var tdArr = trList.eq(i).children("td");
                tdArr.eq(1).html(i);
            }
        }
    </script>
</head>
<body>
<script th:inline="javascript">
    function selBatchInNestSheet(formCode, fieldName, obj) {
        if (obj.checked) {
            $('#cwsNestTable_' + fieldName).find('.row-chk').prop('checked', true);
        } else {
            $('#cwsNestTable_' + fieldName).find('.row-chk').prop('checked', false);
        }
    }

    function delBatch(parentFormCode, formCode, fieldName, moduleCode, cwsId) {
        var ids = '';
        $('#cwsNestTable_' + fieldName).find('input[id=rowId]:checked').each(function (k) {
            if (ids == '') {
                ids = $(this).val();
            } else {
                ids += ',' + $(this).val();
            }
        });
        console.log('delBatch ids', ids);
        if (ids == '') {
            myMsg('请选择记录', 'warn');
            return;
        }

        myConfirm('提示', '您确定要删除么', delBatchCallBack, {parentFormCode, formCode, fieldName, ids, moduleCode, cwsId});
    }

    function delBatchCallBack(params) {
        const {parentFormCode, formCode, fieldName, ids, moduleCode, cwsId} = params
        var url = "/flow/delNestSheetRelated?ids=" + ids + "&formCode=" + parentFormCode + "&formCodeRelated=" + formCode + "&moduleCode=" + moduleCode + "&parentId=" + cwsId;
        var params = {};
        ajaxPost(url, params).then((data) => {
            console.log('data', data);
            myMsg(data.msg);
            if (data.ret == "1") {
                // 如果是编辑状态，则刷新嵌套表
                if ("edit" == [[${op}]]) {
                    refreshNestSheetCtl(fieldName);
                } else {
                    var ary = ids.split(',');
                    for (var i in ary) {
                        console.log('delBatchCallBack ary[' + i + ']=', ary[i]);
                        $("#" + fieldName + "_" + ary[i]).remove();
                        // 移除可能在智能模块添加页插入的tempCwsId_中的id值
                        $("input[name='tempCwsId_" + fieldName + "'][value=" + ary[i] + "]").remove();
                    }
                }

                refreshSerialNo(fieldName);

                callCalculateOnload();

                eventTarget.fireEvent({
                    type: EVENT_TYPE.NEST_DEL,
                    moduleCode: moduleCode,
                    ids: ids,
                });

                // 用于form_js_***调用
                try {
                    onNestAfterDelRow(formCode, ids, cwsId, fieldName);
                }
                catch(e) {}
                try {
                    onNestSheetChange(moduleCode, "del", id, fieldName);
                } catch (e) {}
            }
        });
    }

    // 将单元格的paddin置为0，以使得嵌套表格2占满全部单元格
    $('#nestsheet_[(${nestFieldName})]').closest('td').css('padding', '0px');
</script>

<th:block th:if="${op eq 'edit' || op eq 'view'}">
    <script th:inline="javascript">
        // 计算控件回调
        function callByNestSheet(nestSheetSums, formCode, nestFieldName) {
            console.log('macro_js_nestsheet callByNestSheet nestSheetSums', JSON.stringify(nestSheetSums));
            if (nestSheetSums != null) {
                console.log('callByNestSheet typeof (nestSheetSums)', typeof (nestSheetSums));
                if (typeof (nestSheetSums) == 'object') {
                    var keys = '';
                    // 20220730 将o由原来的sum(nest.je)中的je改为计算控件的字段名
                    for (var o in nestSheetSums) {
                        if (keys.indexOf(',' + o + ',') != -1) {
                            // 跳过已正常取得的字段，因为可能在sum时两个嵌套表中都含有同名的字段，而其中一个是有formCode属性的
                            continue;
                        }
                        console.log('keys', keys);
                        var $ctl = $("input[name='" + o + "'][nestField='" + nestFieldName + "']");
                        if (!$ctl[0]) {
                            // 向下兼容会带来问题，如果在sum时两个嵌套表中都含有同名的字段，会导致出现问题，故需带有formCode属性的计算控件字段记住
                            // 向下兼容，旧版的sum型计算控件中没有formCode
                            $ctl = $("input[name='" + o + "']");
                        } else {
                            if (keys == '') {
                                keys = ',' + o + ',';
                            } else {
                                keys += o + ',';
                            }
                        }
                        $ctl.val(nestSheetSums[o]);
                    }
                }
            }
        }

        // 注意仅可编辑时才调用，否则例如：当事务所内资审核时，查看项目详情，切换选项卡，看以往审核记录，查看记录的详情，
        // 再回到审核流程处理界面时，callByNestSheet会将以往审核记录的值赋予给流程表单中的同名字段，
        // 即认定栏投资方上方的那些字段（均为计算控件，但实际上已无法计算，因为投资方嵌套表中没有对应的列）
        if ("edit" == [[${op}]]) {
            callByNestSheet([(${jsonSums})], [[${formCode}]], [[${nestFieldName}]]);
        }

        function addRow(cwsId, parentFormCode, moduleCode, flowId, nestFieldDesc, formName, nestFieldName, moduleName) {
            openSmartModuleRelateTableDrawer(1, {parentId: cwsId, moduleCode: parentFormCode, moduleCodeRelated: moduleCode, flowId: flowId, pageType: 'add_relate', nestFieldDesc: nestFieldDesc, parentFormName: formName, nestFieldName: nestFieldName, moduleName: moduleName});
        }

        function editRow(id, cwsId, parentFormCode, moduleCode, flowId, nestFieldDesc, formName, nestFieldName, moduleName) {
            openSmartModuleRelateTableDrawer(2, {parentId: cwsId, id: id, moduleCode: parentFormCode, moduleCodeRelated: moduleCode, flowId: flowId, pageType: 'edit_relate', nestFieldDesc: nestFieldDesc, parentFormName: formName, nestFieldName: nestFieldName, moduleName: moduleName});
        }

        function delCallBack(params) {
            const {id, nestFieldName, parentFormCode, formCode, moduleCode, cwsId} = params;
            var url = "/flow/delNestSheetRelated?ids=" + id + "&formCode=" + parentFormCode + "&formCodeRelated=" + formCode + "&moduleCode=" + moduleCode + "&parentId=" + cwsId;
            var params = {};
            ajaxPost(url, params).then((data) => {
                console.log('data', data);
                myMsg(data.msg);
                if (data.ret == "1") {
                    $("#" + nestFieldName + "_" + id).remove();
                    refreshSerialNo(nestFieldName);

                    url = $('#cwsNestTable_' + nestFieldName).attr('url');
                    loadNestCtl(url, 'nestsheet_' + nestFieldName, [[${curPage}]], [(${pageSize})], getConds(nestFieldName), [[${formName}]]);

                    eventTarget.fireEvent({
                        type: EVENT_TYPE.NEST_DEL,
                        moduleCode: moduleCode,
                        ids: id,
                    });

                    // 移除可能在智能模块添加页插入的tempCwsId_中的id值
                    $("input[name='tempCwsId_" + nestFieldName + "'][value=" + id + "]").remove();

                    // callCalculateOnload();
                    try {
                        onNestAfterDelRow(formCode, id, cwsId, nestFieldName);
                    }
                    catch(e) {}
                    // 用于form_js_***.jsp调用
                    try {
                        onNestSheetChange(moduleCode, "del", id, nestFieldName);
                    } catch (e) {}
                }
            });
        }

        function delRow(id, nestFieldName, parentFormCode, formCode, moduleCode, cwsId) {
            console.log('delRow id', id);
            myConfirm('提示', '您确定要删除么', delCallBack, {id, nestFieldName, parentFormCode, formCode, moduleCode, cwsId});
        }

        function importForSheet(parentId, moduleCode, parentFormCode, flowId, nestFieldName) {
            openImportExcelModal(parentId, moduleCode, parentFormCode, flowId, nestFieldName, "nest_sheet");
        }

        function doExportExcelRelate(cwsId, parentFormCode, formCode, nestFieldTitle) {
            exportExcelRelate(
                [[${NEST_TYPE_NORMAIL}]],
                cwsId,
                parentFormCode,
                formCode,
                nestFieldTitle
            )
        }

        function sel(parentId, isQuery, selWinUrl, parentFormCode, formCode, nestFieldName, mainId, condFields) {
            if (selWinUrl == '') {
                openWinModuleListNest(parentFormCode, formCode, nestFieldName, "nest_sheet", parentId, mainId, condFields);
            } else {
                openWin(selWinUrl + "?parentFormCode=" + parentFormCode + "&nestFormCode=" + formCode + "&nestFieldName=" + nestFieldName + "&nestType=nest_sheet&parentId=" + parentId + "&mainId=" + mainId, 800, 600);
            }
        }

        try {
            // 在Render中生成了此方法，因为通过loadNestCtl，ajax方式来获取嵌套表格2，所以在此需再调用一下以隐藏列
            hideNestCol();
        }
        catch (e) {}

        function showModule(visitKey, id, quoteFlowId, quoteId, quoteModuleCode, isShowFlow, flowId, moduleCode) {
            if (isShowFlow ==1 && quoteFlowId != -1) {
                openWinFlowShow(quoteFlowId, visitKey);
            }
            else if (quoteId != -1) {
                openWinModuleShow(quoteModuleCode, quoteId, visitKey, {flowId: flowId});
            }
            else {
                // 暂时先用openWinModuleShow替代实现
                // openWinModuleRelateShow(...);
                openWinModuleShow(moduleCode, id, visitKey, {flowId: flowId});
            }
        }
    </script>

	<div th:if="${isSearchable}" class="search-box">
		<th:block th:if="${isQuery}">
			<th:block th:each="cond : ${queryConds}">
				<span class="cond-span"><span class="cond-title">[[${cond.title}]]</span>[(${cond.html})]</span>
				<script>
					[(${cond.script})]
				</script>
			</th:block>
			<span class="cond-span">
			<input type="hidden" name="code" th:value="${moduleCode}" />
			<input type="hidden" name="mainCode" th:value="${mainCode}" />
			<input th:id="'btn' + ${nestFieldName}" class="tSearch" type="button" value="" />
			<script th:inline="javascript">
				$('#btn[(${nestFieldName})]').click(function(e) {
					e.preventDefault();
                    var url = $('#cwsNestTable_' + '[(${nestFieldName})]').attr('url');
                    var isSearch = true;
                    loadNestCtl(url, 'nestsheet_' + [[${nestFieldName}]], [[${curPage}]], [(${pageSize})], getConds([[${nestFieldName}]]), [[${formName}]], isSearch);
				})
			</script>
		</th:block>
	</div>

    <th:block th:if="${isOpShow}">
        <th:block th:if="${op eq 'view' && canExport}">
            <div th:id="'toolbar_' + ${nestFieldName}" class="nest-toolbar">
                <span class="nest-btn" th:onclick="doExportExcelRelate([[${cwsId}]], [[${parentFormCode}]], [[${formCode}]], [[${nestFieldTitle}]])"><i class="fa fa-arrow-circle-o-up link-icon link-icon-edit"></i>导出</span>
            </div>
        </th:block>
        <th:block th:if="${op eq 'edit' && (canAdd || canDel || canImport || canExport || canSel)}">
            <div th:id="'toolbar_' + ${nestFieldName}" class="nest-toolbar">
                <span th:if="${op eq 'edit' && canAdd}" class="nest-btn" th:onclick="addRow('[(${cwsId})]', [[${parentFormCode}]], [[${moduleCode}]], [(${flowId})], [[${jsonEncoded}]], [[${formName}]], [[${nestFieldName}]], [[${moduleName}]])"><i class="fa fa-plus-circle link-icon link-icon-add"></i>添加</span>
                <span th:if="${op eq 'edit' && canDel}" class="nest-btn" th:onclick="delBatch('[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', '[(${moduleCode})]', '[(${cwsId})]')"><i class="fa fa-trash-o link-icon link-icon-del"></i>删除</span>
                <span th:if="${op eq 'edit' && canImport}" class="nest-btn" th:onclick="importForSheet([[${cwsId}]], '[(${moduleCode})]', '[(${parentFormCode})]', [(${flowId})], '[(${nestFieldName})]')"><i class="fa fa-arrow-circle-o-down link-icon link-icon-edit"></i>导入</span>
                <span th:if="${canExport}" class="nest-btn" th:onclick="doExportExcelRelate([[${cwsId}]], [[${parentFormCode}]], [[${formCode}]], [[${nestFieldTitle}]])"><i class="fa fa-arrow-circle-o-up link-icon link-icon-edit"></i>导出</span>
                <span th:if="${op eq 'edit' && canSel && queryId>0}" class="nest-btn" th:onclick="sel([[${cwsId}]], true, '[(${selWinUrl})]', '[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', [(${mainId})], '[(${condFields})]')"><i class="fa fa-check-square-o link-icon link-icon-show"></i>选择</span>
                <span th:if="${op eq 'edit' && canSel}" class="nest-btn" th:onclick="sel([[${cwsId}]], false, '[(${selWinUrl})]', '[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', [(${mainId})], '[(${condFields})]')"><i class="fa fa-check-square-o link-icon link-icon-show"></i>选择</span>
            </div>
        </th:block>
    </th:block>

    <table th:id="'cwsNestTable_' + ${nestFieldName}" th:attr="nestField=${nestFieldName},url=${url},isShowChk=${isShowChk},formCode=${formCode}" class="tabStyle_1" style="width:100%;margin:0" border="0" align="center" cellpadding="2" cellspacing="0">
        <thead>
        <tr align="center" class="cwsThead">
            <td class="td-chk" align="center" th:style="'width: 35px; display: ' + ${isShowChk?'':'none'}">
            <input type="checkbox" th:onclick="selBatchInNestSheet([[${formCode}]], [[${nestFieldName}]], this)" />
            </td>
            <td th:style="'width:60px;display:' + ${isNoShow==1?'':'none'}">
            <!--ID-->
            序号
            </td>
            <td th:each="col : ${cols}" th:attr="fieldName=${col.fieldName},macroType=${col.macroType}" th:width="${col.fieldsWidth}">[[${col.title}]]</td>
            <th:block th:if="${isOpShow}">
            <td class="tdOperate" style="width:160px; text-align: center">
                操作
            <!--<a th:if="${op eq 'edit' && canAdd}" class="link-btn" title="增加" style="cursor:pointer" th:onclick="addRow('[(${cwsId})]', [[${parentFormCode}]], [[${moduleCode}]], [(${flowId})], [[${jsonEncoded}]], [[${formName}]], [[${nestFieldName}]], [[${moduleName}]])">
                <i class="fa fa-plus-circle link-icon link-icon-add"></i>
            </a>
            <a th:if="${op eq 'edit' && canImport}" class="link-btn" title="导入" style="cursor:pointer" th:onclick="importForSheet([[${cwsId}]], '[(${moduleCode})]', '[(${parentFormCode})]', [(${flowId})], '[(${nestFieldName})]')"><i class="fa fa-arrow-circle-o-down link-icon link-icon-edit"></i></a>
            <a th:if="${canExport}" class="link-btn" title="导出" style="cursor:pointer" onclick="doExportExcelRelate()"><i class="fa fa-arrow-circle-o-up link-icon link-icon-edit"></i></a>
            <a th:if="${op eq 'edit' && canSel && queryId>0}" class="link-btn" title="选择" style="cursor:pointer" th:onclick="sel([[${cwsId}]], true, '[(${selWinUrl})]', '[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', [(${mainId})], '[(${condFields})]')"><i class="fa fa-check-square-o link-icon link-icon-show"></i></a>
            <a th:if="${op eq 'edit' && canSel}" class="link-btn" title="选择" style="cursor:pointer" th:onclick="sel([[${cwsId}]], false, '[(${selWinUrl})]', '[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', [(${mainId})], '[(${condFields})]')"><i class="fa fa-check-square-o link-icon link-icon-show"></i></a>
            <a th:if="${op eq 'edit' && canDel}" class="link-btn" title="批量删除" style="cursor:pointer" th:onclick="delBatch('[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', '[(${moduleCode})]', '[(${cwsId})]')"><i class="fa fa-trash-o link-icon link-icon-del"></i></a>
-->            </td>
            </th:block>
        </tr>
        </thead>
        <body>
        <tr th:each="row : ${rows}" align="center" th:id="${nestFieldName + '_' + row.id}" th:class="${row.cls}">
            <td class="td-chk" align="center" th:style="'display: ' + ${isShowChk?'':'none'}">
                <input id="rowId" th:value="${row.id}" class="row-chk" type="checkbox"/>
            </td>
            <td editable=0 th:title="'ID：' + ${row.id}" th:style="'display: ' + ${isNoShow==1?'':'none'}">
                [[${row.k}]]
            </td>
            <td th:each="field : ${row.fields}" th:align="${field.align}">
                [(${field.html})]
            </td>
            <td>
                <a th:if="${op=='edit' && canEdit}" class="link-btn" title="修改" style="cursor:pointer"
                   th:onclick="editRow([(${row.id})], [[${cwsId}]], [[${parentFormCode}]], [[${moduleCode}]], [(${flowId})], [[${jsonEncoded}]], [[${formName}]], [[${nestFieldName}]], [[${moduleName}]])"><i
                        class="fa fa-edit link-icon link-icon-edit"></i></a>
                <a th:if="${!(op=='edit' && canEdit)}" class="link-btn" title="查看" style="cursor:pointer"
                   th:onclick="showModule('[(${row.visitKey})]', [(${row.id})], [(${row.quoteFlowId})], [(${row.quoteId})], [[${sourceMoudleCode}]], [(${isShowFlow})], [(${flowId})], [[${moduleCode}]])"><i
                        class="fa fa-file-text-o link-icon link-icon-show"></i></a>
                <a th:if="${op=='edit' && canDel}" class="link-btn" title="删除" style="cursor:pointer"
                   th:onclick="delRow([(${row.id})], '[(${nestFieldName})]', '[(${parentFormCode})]', '[(${formCode})]', '[(${moduleCode})]', [(${cwsId})])"><i class="fa fa-trash-o link-icon link-icon-del"></i></a>
            </td>
        </tr>
        [(${trStatHtml})]
        </body>
    </table>
</th:block>
<th:block th:if="${op ne 'edit' && op ne 'view'}">
    <script th:inline="javascript">
    // 添加主表记录时，编辑已添加的嵌套表的记录，需通过updateRow更新页面上的记录
    function updateRow(formCode, fdaoId, tds, token, nestFieldName, moduleCode) {
        var isNoShow = [(${isNoShow})]==1;
        var isShowChk = [(${isShowChk})];
        var dlt = 2;
        // 复选框列及序号列是隐藏的，仍存在
        /*if (isShowChk && isNoShow) {
            dlt = 2;
        }
        else if (isShowChk) {
            dlt = 1;
        }
        else if (isNoShow) {
            dlt = 1;
        }*/
        console.log('updateRow tds', tds, 'token', token, 'dlt', dlt);
        var ary = tds.split(token);
        for (var k in ary) {
            $('#' + nestFieldName + '_' + fdaoId + ' td:eq(' + (parseInt(k) + parseInt(dlt)) + ')').html(ary[k]);
        }

        /*$('#' + nestFieldName + '_' + fdaoId).children().each(function (k) {
            if (k - dlt >= ary.length)
                return;

            // 不显示的复选框及序号列是隐藏的
            $(this).html(ary[k - dlt] ? ary[k - dlt] : '');
        });*/
        callCalculateOnload();

        eventTarget.fireEvent({
            type: EVENT_TYPE.NEST_EDIT,
            moduleCode: moduleCode,
            nestFieldName: nestFieldName,
            id: fdaoId,
        });

        try {
            onNestSheetChange(moduleCode, "update", fdaoId);
        } catch (e) {}
    }

    function addRow(cwsId, parentFormCode, moduleCode, flowId, nestFieldDesc, formName, nestFieldName, moduleName) {
        openSmartModuleRelateTableDrawer(1, {parentId: cwsId, moduleCode: parentFormCode, moduleCodeRelated: moduleCode, flowId: flowId, pageType: 'add_relate', nestFieldDesc: nestFieldDesc, parentFormName: formName, nestFieldName: nestFieldName, moduleName: moduleName});
    }

    function editRow(id, cwsId, parentFormCode, moduleCode, flowId, nestFieldDesc, formName, nestFieldName, moduleName) {
        openSmartModuleRelateTableDrawer(2, {parentId: cwsId, id: id, moduleCode: parentFormCode, moduleCodeRelated: moduleCode, flowId: flowId, pageType: 'edit_relate', nestFieldDesc: nestFieldDesc, parentFormName: formName, nestFieldName: nestFieldName, moduleName: moduleName});
    }

    function delRow(id, nestFieldName, parentFormCode, formCode, moduleCode, cwsId) {
        myConfirm('提示', '您确定要删除么', delCallBack, {id, nestFieldName, parentFormCode, formCode, moduleCode, cwsId});
    }

    function delCallBack(params) {
        const {id, nestFieldName, parentFormCode, formCode, moduleCode, cwsId} = params;
        var url = "/flow/delNestSheetRelated?ids=" + id + "&formCode=" + parentFormCode + "&formCodeRelated=" + formCode + "&moduleCode=" + moduleCode + "&parentId=" + cwsId;
        var params = {};
        ajaxPost(url, params).then((data) => {
            console.log('data1', data);
            myMsg(data.msg);
            if (data.ret == "1") {
                $("#" + nestFieldName + "_" + id).remove();
                refreshSerialNo(nestFieldName);

                callCalculateOnload();

                // 移除可能在智能模块添加页插入的tempCwsId_中的id值
                $("input[name='tempCwsId_" + nestFieldName + "'][value=" + id + "]").remove();

                eventTarget.fireEvent({
                    type: EVENT_TYPE.NEST_DEL,
                    moduleCode: moduleCode,
                    ids: id,
                });

                try {
                    onNestAfterDelRow(formCode, id, cwsId, nestFieldName);
                }
                catch(e) {}
                // 用于form_js_***中调用
                try {
                    onNestSheetChange(moduleCode, "del", id, nestFieldName);
                } catch (e) {}
            }
        });
    }

    function importForSheet(parentId, moduleCode, parentFormCode, flowId, nestFieldName) {
        openImportExcelModal(parentId, moduleCode, parentFormCode, flowId, nestFieldName, "nest_sheet");
    }

    function sel(parentId, isQuery, selWinUrl, parentFormCode, formCode, nestFieldName, mainId, condFields) {
        openWinModuleListNest(parentFormCode, formCode, nestFieldName, "nest_sheet", parentId, mainId, condFields);
    }

    function showModule(visitKey, id, moduleCode, flowId) {
        openWinModuleShow(moduleCode, id, visitKey, {flowId: flowId});
    }
    </script>

    <div th:id="'toolbar_' + ${nestFieldName}" th:if="${canAdd || canDel || canSel}" class="nest-toolbar">
        <span th:if="${canAdd}" class="nest-btn" th:onclick="addRow('[(${cwsId})]', [[${parentFormCode}]], [[${moduleCode}]], [(${flowId})], [[${jsonEncoded}]], [[${formName}]], [[${nestFieldName}]], [[${moduleName}]])"><i class="fa fa-plus-circle link-icon link-icon-add"></i>添加</span>
        <span th:if="${canDel}" class="nest-btn" th:onclick="delBatch('[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', '[(${moduleCode})]', '[(${cwsId})]')"><i class="fa fa-trash-o link-icon link-icon-del"></i>删除</span>
        <span th:if="${false && canImport}" class="nest-btn" th:onclick="importForSheet([[${cwsId}]], '[(${moduleCode})]', '[(${parentFormCode})]', [(${flowId})], '[(${nestFieldName})]')"><i class="fa fa-arrow-circle-o-down link-icon link-icon-edit"></i>导入</span>
        <span th:if="${canSel && queryId>0}" class="nest-btn" th:onclick="sel([[${cwsId}]], true, '[(${selWinUrl})]', '[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', [(${mainId})], '[(${condFields})]')"><i class="fa fa-check-square-o link-icon link-icon-show"></i>选择</span>
        <span th:if="${canSel}" class="nest-btn" th:onclick="sel([[${cwsId}]], false, '[(${selWinUrl})]', '[(${parentFormCode})]', '[(${formCode})]', '[(${nestFieldName})]', [(${mainId})], '[(${condFields})]')"><i class="fa fa-check-square-o link-icon link-icon-show"></i>选择</span>
    </div>
    <table th:id="'cwsNestTable_' + ${nestFieldName}" th:attr="nestField=${nestFieldName},url=${url},isShowChk=${isShowChk},formCode=${formCode}" class="tabStyle_1" style="width:100%;margin:0px" border="0" align="center" cellpadding="2" cellspacing="0">
        <thead>
        <tr align="center" class="cwsThead">
            <td class="td-chk" align="center" th:style="'width: 35px; display: ' + ${isShowChk?'':'none'}">
            <input type="checkbox" th:onclick="selBatchInNestSheet([[${formCode}]], [[${nestFieldName}]], this)" />
            </td>
            <td th:style="'width:60px;display: ' + ${isNoShow==1?'':'none'}">序号</td>
            <td th:each="col : ${cols}" th:attr="fieldName=${col.fieldName},macroType=${col.macroType}" th:width="${col.fieldsWidth}">[[${col.title}]]</td>
            <td class="tdOperate" style="width:160px; text-align: center">
                操作
            </td>
        </tr>
        </thead>
        <body>
            <tr th:each="row : ${rows}" align="center" th:id="${nestFieldName + '_' + row.id}" th:class="${row.cls}">
                <td class="td-chk" align="center" th:style="'display: ' + ${isShowChk?'':'none'}">
                    <input id="rowId" th:value="${row.id}" class="row-chk" type="checkbox"/>
                </td>
                <td editable=0 th:title="'ID：' + ${row.id}" th:style="'display: ' + ${isNoShow==1?'':'none'}">
                    [[${row.k}]]
                </td>
                <td th:each="field : ${row.fields}" th:align="${field.align}">
                    [[${field.html}]]
                </td>
                <td th:if="${isOpShow}">
                    <a th:if="${canEdit}" class="link-btn" title="修改" style="cursor:pointer"
                       th:onclick="editRow([(${row.id})], [[${cwsId}]], [[${parentFormCode}]], [[${moduleCode}]], [(${flowId})], [[${jsonEncoded}]], [[${formName}]], [[${nestFieldName}]], [[${moduleName}]])"><i
                            class="fa fa-edit link-icon link-icon-edit"></i></a>
                    <a th:if="${!canEdit}" class="link-btn" title="查看" style="cursor:pointer"
                       th:onclick="showModule('', [(${row.id})], '[(${moduleCode})]', [(${flowId})])"><i
                            class="fa fa-file-text-o link-icon link-icon-show"></i></a>
                    <a th:if="${canDel}" class="link-btn" title="删除" style="cursor:pointer"
                       th:onclick="delRow([(${row.id})], '[(${nestFieldName})]', '[(${parentFormCode})]', '[(${formCode})]', '[(${moduleCode})]', [(${cwsId})])"><i class="fa fa-trash-o link-icon link-icon-del"></i></a>
                </td>
            </tr>
        </body>
    </table>
</th:block>

<div th:if="${isPage == 1 && (op eq 'edit' || op eq 'view')}" class="paginator" th:id="'paginator' + ${nestFieldName}" style="padding-left:10px"></div>
<script th:inline="javascript">
    function fireEventSelect_[(${moduleCode})]() {
        eventTarget.fireEvent({
            type: EVENT_TYPE.NEST_SELECT,
            moduleCode: moduleCode
        });
    }

	var aryAlign_[(${nestFieldName})] = new Array();
    [# th:each="align, stat : ${fieldsAlign}"]
    aryAlign_[(${nestFieldName})][(${stat.index})] = [[${align}]];
    [/]

	// 记录添加的嵌套表格2记录的ID
	function addTempCwsId(formCode, cwsId, formName, nestFieldName) {
		console.log('addTempCwsId formCode', formCode);
		console.log('addTempCwsId cwsId', cwsId);
		var name = [[${NAME_TEMP_CWS_IDS}]] + '_' + nestFieldName;
		var inp;
		try {
			inp = document.createElement('<input type="hidden" name="' + name + '" />');
		} catch (e) {
			inp = document.createElement("input");
			inp.type = "hidden";
			inp.name = name;
		}
		inp.value = cwsId;

		console.log('formName', formName);
		// 当嵌套表中的嵌套表插入数据时 smartModuleRelateTableDrawer 中传入了formName
		if (formName) {
			fo('spanTempCwsIds', formName).appendChild(inp);
		} else {
			fo('spanTempCwsIds').appendChild(inp);
		}
	}

function decodeJSON(jsonString) {
	jsonString = jsonString.replace(/%dq/gi, '"');
	jsonString = jsonString.replace(/%sq/gi, "'");
	jsonString = jsonString.replace(/%eq/gi, '=');
	jsonString = jsonString.replace(/%lb/gi, "{");
	jsonString = jsonString.replace(/%rb/gi, "}");
	jsonString = jsonString.replace(/%lt/gi, "<");
	jsonString = jsonString.replace(/%gt/gi, ">");
	jsonString = jsonString.replace(/%co/gi, ",");
	// 不能出现换行，否则insertRow中eval的时候会报错
	// jsonString = jsonString.replace(/%rn/g, "\r\n")
	// jsonString = jsonString.replace(/%n/g, "\n")
	return jsonString;
}

// 新增后插入数据
// 或从module_list_nest_sel.jsp选择数据后调用
var idNum = 1000;
// moduleCode 为父级模块的编码
function insertRow(moduleCodeRelated, formCode, fdaoId, tds, token, isPull, flowId, nestFieldDescEncoded, cwsId, moduleCode, formName, nestFieldName, parentFormCode) {
	console.log('insertRow nestFieldDesc', nestFieldDescEncoded);
    // 拉单时 nestFieldDescEncoded 为 json，而添加时则为字符串
	if (typeof nestFieldDescEncoded == 'object') {
        nestFieldDesc = nestFieldDescEncoded;
    } else {
        nestFieldDesc = JSON.parse(decodeJSON(nestFieldDescEncoded));
    }
    console.log('nestFieldDesc', nestFieldDesc);
    console.log('nestFieldName', nestFieldName);

	var isNoShow = nestFieldDesc.isNoShow;

	var ary = tds.split(token);
	var cls = '';

	if (nestFieldDesc.isAddHighlight == 1) {
		// 如果是来自于拉单
		if (isPull) {
			cls = 'row-pull';
		}
		else {
			cls = 'row-add';
		}
	}

	var trHTML = "<tr id='" + nestFieldName + "_" + fdaoId + "' class='" + cls + "'>";

	// 插入复选框，注意 isShowChk并非原本就是在嵌套表的属性中，而是根据添加或编辑操作在此页面中传入的
    var isShowChk = 'true';
    if (formName) {
        isShowChk =  $(o(formName)).find("#cwsNestTable_" + nestFieldName).attr('isShowChk');
    } else {
        isShowChk = $("#cwsNestTable_" + nestFieldName).attr('isShowChk');
    }
	if (isShowChk == 'true') {
		trHTML += "<td align='center' class='td-chk'><input id='rowId' type='checkbox' value='" + fdaoId + "' class='row-chk'></td>";
	}

	// 插入序号列
	var trList;
    if (formName) {
        trList = $(o(formName)).find("#cwsNestTable_" + nestFieldName).find("tr");
    } else {
        trList = $("#cwsNestTable_" + nestFieldName).find("tr");
    }
    var trLen = trList.length;
    // trHTML += "<td title='ID：" + fdaoId + "' align='center'><input id=\"rowId\" type=\"checkbox\" value=\"" + fdaoId + "\" class=\"row-chk\"></td>";
    trHTML += "<td title='ID：" + fdaoId + "' align='center' style=\"display: " + (isNoShow == 1 ? "" : "none") + "\">" + trLen + "</td>";

	for (var i=0; i< ary.length; i++) {
	    var alignArr = eval('aryAlign_' + nestFieldName);
	    console.log('insertRow align', alignArr);
	    var align = alignArr[i] || 'center';
		trHTML += "<td align='" + align + "'>" + ary[i] + "</td>";
	}

	trHTML += "<td align='center'>";
	idNum++;
	if (nestFieldDesc.canEdit == 'true') {
		trHTML += '<a class="link-btn" title="修改" style="cursor:pointer" onclick="editRow(' + fdaoId + ',' + cwsId + ',\'' + moduleCode + '\',\'' + moduleCodeRelated + '\',' + flowId + ',\'' + nestFieldDescEncoded + '\', \'' + formName + '\',\'' + nestFieldName + '\')"><i class="fa fa-edit link-icon link-icon-edit"></i></a>';
	} else {
		trHTML += '<a class="link-btn" title="查看" style="cursor:pointer" onclick="showModule(\'\', ' + fdaoId + ',' + moduleCode + ',' + flowId + ')"><i class="fa fa-file-text-o link-icon link-icon-show"></i></a>';
	}
	if (nestFieldDesc.canDel == 'true') {
		trHTML += '<a class="link-btn" title="删除" style="cursor:pointer" onclick="delRow(' + fdaoId + ',\'' + nestFieldName + '\',\'' + parentFormCode + '\',\'' + formCode + '\',\'' + moduleCode + '\',\'' + cwsId + '\')"><i class="fa fa-trash-o link-icon link-icon-del"></i></a>';
	}
	trHTML += "</td>";
	trHTML += "</tr>";

    if (formName) {
        $(o(formName)).find("#cwsNestTable_" + nestFieldName).append(trHTML);
    } else {
        $("#cwsNestTable_" + nestFieldName).append(trHTML);
    }
	if (nestFieldDesc.canEdit == 'true') {
		$("#imgBtnEdit" + idNum).hover(
		  function () {
			$(this).toggleClass( "imgBtnHover" );
		  },
		  function () {//mouseout
			$(this).toggleClass( "imgBtnHover" );
		  }
		);
	}
	if (nestFieldDesc.canDel == 'true') {
		$("#imgBtnDel" + idNum).hover(
		  function () {
			$(this).toggleClass( "imgBtnHover" );
		  },
		  function () {
			$(this).toggleClass( "imgBtnHover" );
		  }
		);
	}

    eventTarget.fireEvent({
		type: EVENT_TYPE.NEST_ADD,
		moduleCode: moduleCodeRelated
	});

	// 用于form_js_***.jsp调用
	try {
		onNestInsertRow(moduleCodeRelated, formCode, fdaoId, tds, token, cwsId, nestFieldName);
	} catch (e) {
	}
}

$(function () {
	initImgBtn();
});

function initImgBtn() {
	$(".imgBtn").hover(
	  function () {
		$(this).toggleClass( "imgBtnHover" );
	  },
	  function () {//mouseout
		$(this).toggleClass( "imgBtnHover" );
	  }
	);
}

[# th:if="${op eq 'edit'}"]
// 防止内资审核点开项目，在选项卡中看内资审核以往记录，查看详情时覆盖了流程处理页面上的投资方明细表中的同名方法
// 带分页重新加载
function reloadNestSheetCtl(moduleCode, nestFieldName, formName, id) {
    var url = $('#cwsNestTable_' + nestFieldName).attr('url');
	loadNestCtl(url, 'nestsheet_' + nestFieldName, [(${curPage})], [(${pageSize})], getConds(nestFieldName), formName).then(() => {
		console.log('reloadNestSheetCtl fireEvent');
		// 如果 id 有值，则为编辑嵌套表后刷新，传自于：processHandleView.vue中的handleSmartModuleCallBack
		if (id) {
            eventTarget.fireEvent({
                type: EVENT_TYPE.NEST_EDIT,
                moduleCode: moduleCode,
                nestFieldName: nestFieldName,
                id: id
            });
        }

	});
}
[/]

[# th:if="${isPage==1 && (op eq 'edit' || op eq 'view')}"]
var pageSize = [(${pageSize})];
var curPage = [(${curPage})];
var total = [(${total})];
// 初始化分页
var paging[(${nestFieldName})] = new MyPaging('#paginator[(${nestFieldName})]', {
	size: pageSize,
	total: total,
	current: curPage,
	prevHtml: '上一页',
	nextHtml: '下一页',
	layout: 'total, totalPage, sizes, prev, pager, next, jumper',
	jump: function() {
		var _this = this; // 模拟ajax获取数据
		_this.setTotal(total);

		// 如果当前分页不等于点击的页码，才可以loadNestCtl，否则会陷入循环
		if (_this.current != curPage || _this.size != pageSize) {
			var conds = getConds([[${nestFieldName}]]);
			console.log('MyPaging conds', conds);
            var url = $('#cwsNestTable_' + '[(${nestFieldName})]').attr('url');
            var isSearch = true;
            loadNestCtl(url, 'nestsheet_[(${nestFieldName})]', _this.current, _this.size, conds, [[${formName}]], isSearch);
		}
	}
});

$('.jumpBtn').on('click', function() {
	paging[(${nestFieldName})].setCurrent(1);
});
[/]

	function getConds(nestFieldName) {
		var conds = "";
		var fields = $('#nestsheet_' + nestFieldName).find('.search-box').find('input,select,textarea');
		$.each(fields, function (i, field) {
			if ('' == conds) {
				conds = field.name + '=' + encodeURI(field.value);
			} else {
				conds += "&" + field.name + '=' + encodeURI(field.value);
			}
		});
		if ('' != conds) {
			conds += "&action=search";
		}
		return conds;
	}

	function bindNestTableMouseEvent() {
		$("table[id^='cwsNestTable_'] td").mouseout(function () {
			if ($(this).parent().parent().get(0).tagName != "THEAD")
				$(this).parent().find("td").each(function (i) {
					$(this).removeClass("tdOver");
				});
		});

		$("table[id^='cwsNestTable_'] td").mouseover(function () {
			if ($(this).parent().parent().get(0).tagName != "THEAD")
				$(this).parent().find("td").each(function (i) {
					$(this).addClass("tdOver");
				});
		});
	}

	bindNestTableMouseEvent();

	// 注意如果在此初始化event，则主表单中有N个嵌套表格2，就会被初始化N个对应的事件
	// 所以应放在form_js中
	/*function onNestChange(event) {
		console.log(event);
	}

	$(function() {
		eventTarget.addEvent(EVENT_TYPE.NEST_ADD, onNestChange);
		eventTarget.addEvent(EVENT_TYPE.NEST_EDIT, onNestChange);
		eventTarget.addEvent(EVENT_TYPE.NEST_DEL, onNestChange);
	});*/

	// 按行分组合并单元格
	function autoMergeCells(table, isPropStat, dlt, rowGroupFields) {
		const rows = table.rows;
		let rowLen = isPropStat ? rows.length - 1 : rows.length;
		for (let col = rows[0].cells.length - 1; col >=dlt ; col--) {
			if (rowGroupFields.some((val) => (val + dlt) == col)) {
				console.log('col', col, 'dlt', dlt);
				for (let row = rowLen-1; row >= 1 ; row--) {
					const currentCell = rows[row].cells[col];
					const previousCell = rows[row - 1].cells[col];
					if (currentCell.textContent === previousCell.textContent) {
						let isSame = true;
						// 判断其左侧的每一列，内容是否相同，如果相同，才能合并，当col为0时，是序号列
						for (let colIndex = col; colIndex>=2; colIndex--) {
							const currentCellLeft = rows[row].cells[colIndex-1];
							const previousCellLeft = rows[row - 1].cells[colIndex-1];
							if (currentCellLeft.textContent != previousCellLeft.textContent) {
								isSame = false;
								break;
							}
						}
						if (!isSame)
							continue;

						console.log('currentCell', currentCell, 'col', col);
						previousCell.setAttribute('rowspan', (currentCell.rowSpan || 1) + 1);
						currentCell.parentNode.removeChild(currentCell);
					}
				}
			}
		}
	}

	// 匿名函数
	(function () {
		var isShowChk = [(${isShowChk})];
		var isNoShow = [(${isNoShow})]==1;
		var isPropStat = [(${isPropStat})];
		var dlt = 0;
		if (isShowChk) {
			dlt += 1;
		}
		if (isNoShow) {
			dlt += 1;
		}

		let rowGroupFields = [(${rowGroupFields})];
		console.log('rowGroupFields', rowGroupFields);
		if (rowGroupFields.length > 0) {
			autoMergeCells($("#cwsNestTable_[(${nestFieldName})]")[0], isPropStat, dlt, rowGroupFields);
		}
	})();

	function autoMergeHeaders(table, dlt, groupFields) {
        if (!table) {
            // 当嵌套表不可写时，table为undefined
            return;
        }

		const rows = table.rows;
		let leftHeader = '', curHeader = '';
		let curIndex = -1;
		let children = '';
		let row = rows[0];
		for (let col = 0; col < row.cells.length; col++) {
			if (col < dlt) {
				row.cells[col].setAttribute("rowspan", 2);
				continue;
			}
			curHeader = groupFields[col - dlt];
			console.log('curHeader', curHeader, 'col', col, 'dlt', dlt);
			if (!curHeader) {
				console.log('no group', row.cells[col]);
				row.cells[col].setAttribute("rowspan", 2);
				leftHeader = '';
				curIndex = -1;
			} else {
				console.log('group', row.cells[col]);
				if (curHeader != leftHeader) {
					leftHeader = curHeader;
					row.cells[col].setAttribute("colspan", 1);
					$(row.cells[col]).text(curHeader);
					$(row.cells[col]).attr('align', 'center');
					curIndex = col;
					children += $(row.cells[col]).prop('outerHTML');
				} else {
					var colspan = parseInt(row.cells[curIndex].getAttribute("colspan"));
					row.cells[curIndex].setAttribute("colspan", colspan + 1);
					children += $(row.cells[col]).prop('outerHTML');
					row.cells[col].parentNode.removeChild(row.cells[col]);
					console.log('row.cells[' + col + '].parentNode', row.cells[col].parentNode);
					col --;
					dlt --;
				}
			}
		}

		console.log('children', children);
		$(table.rows[0]).after(children);
	}

    $('#toolbar_[(${nestFieldName})]').on('mouseover', '.nest-btn', function(e) {
        $(this).addClass("nest-btn-hover");
    });
    $('#toolbar_[(${nestFieldName})]').on('mouseout', '.nest-btn', function(e) {
        $(this).removeClass("nest-btn-hover");
    });

    // 对表头进行分组
	// 匿名函数
	(function () {
        var isShowChk = [(${isShowChk})];
        var isNoShow = [(${isNoShow})]==1;

		var dlt = 0;
		if (isShowChk) {
			dlt += 1;
		}
		if (isNoShow) {
			dlt += 1;
		}

		let groupFields = [(${groupFields})];
		let isGroup = false;
		for (let j in groupFields) {
			if (groupFields[j]) {
				isGroup = true;
				break;
			}
		}
		if (isGroup) {
			autoMergeHeaders($("#cwsNestTable_[(${nestFieldName})]")[0], dlt, groupFields);
		}
	})();
</script>
</body>
</html>